const jwt = require("jsonwebtoken");
const fs = require("fs");
const path = require("path");

// 获取私钥和公钥
const privateKey = fs.readFileSync(path.join(__dirname, "../config/private.key"), "utf-8");
const publicKey = fs.readFileSync(path.join(__dirname, "../config/public.key"), "utf-8");

/**
 * 设置token
 * @param {*} playload 用户信息
 * @param {*} expiresIn 时效（s）
 * @param {*} algorithm 加密方式
 * @returns
 */
const setToken = (playload, expiresIn = 60 * 60 * 24 * 10, algorithm = "RS256") => {
  try {
    const token = jwt.sign(playload, privateKey, {
      expiresIn,
      algorithm,
    });
    return token;
  } catch (error) {
    return "";
  }
};

/**
 * 验证token
 * @param {*} token token
 */

const verifyToken = (token) => {
  try {
    const flag = jwt.verify(token, publicKey, {
      algorithms: ["RS256"],
    });
    return flag;
  } catch (error) {
    return false;
  }
};

module.exports = {
  setToken,
  verifyToken,
};
